
const http = (method,url,data,options={}) =>{
  return new Promise(function(resolve, reject) {
    uni.request({
      method,
      url,
      data,
      header: options.header ? options.header : {},
      ...options,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    });
  })
}

export const upload = (url,data,options={}) =>{
  return new Promise(function(resolve, reject) {
    const uploadTask = uni.uploadFile({
      url,
      filePath: data.filePath,
      name: data.name,
      formData: data.formData, // 数据类型是普通对象不是formData对象
      header: options.header ? options.header : {},
      ...options,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })
    // 上传进度
    uploadTask.onProgressUpdate(res => {
      options.onUploadProgress && options.onUploadProgress(res)
    })
  })
}

export const download = (url,data,options={}) =>{
  return new Promise(function(resolve, reject) {
    const downloadTask = uni.downloadFile({
      url,
      data,
      header: options.header ? options.header : {},
      ...options,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })
    // 下载进度
    downloadTask.onProgressUpdate(res => {
      options.onDownloadProgress && options.onDownloadProgress(res)
    })
  })
}

export const get = (url,data,options) => http('GET',url,data,options)
export const post = (url,data,options) => http('POST',url,data,options)
export const put = (url,data,options) => http('PUT',url,data,options)
export const del = (url,data,options) => http('DELETE',url,data,options)

export default {
  get(url,data,options){
    return http('GET',url,data,options)
  },
  post(url,data,options){
    return http('POST',url,data,options)
  },
  put(url,data,options){
    return http('PUT',url,data,options)
  },
  delete(url,data,options){
    return http('DELETE',url,data,options)
  },
  upload(url,data,options){
    return upload(url,data,options)
  },
  download(url,data,options){
    return download(url,data,options)
  }
}